package com.antony.message0929;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;

public class Sever implements Runnable {
	private ArrayList<Message> msg;
	private Socket sk;
	private Message m;
	private int count;
	private OutputStream out;
	private BufferedReader bs;
	private InputStream in;

	public Sever(ArrayList<Message> msg, Socket sk, int count) {
		this.msg = msg;
		this.sk = sk;
		this.count = count;
	}

	public void run() {
		recieve();
	}

	public void setMsg(BufferedReader bs) throws IOException {
		while (msg.get(count).getStart()) {
			String strMsg = bs.readLine();
			if (strMsg != null)
				msg.get(count).setMsgAll(msg.get(count).getName() + " said:" + strMsg + "\r\n");
		}
	}

	public void recieve() {
		try {
			out = sk.getOutputStream();
			in = sk.getInputStream();
			out.write("welcome!Please enter your username:\r\n".getBytes());
			bs = new BufferedReader(new InputStreamReader(in));
			String name = bs.readLine();
			out.write(("Your username is:" + name + "\r\n").getBytes());
			m = new Message(name, out, msg);
			count = msg.size();
			msg.add(count, m);
			msg.get(count).setMsgAll(name + " is on line.\r\n");
			setMsg(bs);
			out.close();
			in.close();
			sk.close();
			msg.remove(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
